package com.syh.jn.scm.service.impl.downstream.finance;

import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.downstream.entity.finance.DownIncomeBill;
import com.syh.jn.scm.domain.downstream.entity.finance.DownStatementAccountBill;
import com.syh.jn.scm.domain.downstream.event.DownIncomeBillEvent;
import com.syh.jn.scm.domain.downstream.event.DownStatementAccountBillEvent;
import com.syh.jn.scm.domain.downstream.repository.finance.DownIncomeBillRepository;
import com.syh.jn.scm.dto.downstream.finance.DownIncomeBillVo;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.service.api.downstream.finance.DownIncomeBillService;
import com.syh.jn.scm.service.api.downstream.finance.enums.DownIncomeBillEnum;
import com.syh.jn.scm.service.api.downstream.finance.enums.DownStatementAccountBillEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Date:2018/7/19
 * Author:Clown
 * 下游收入单service实现;
 */
@Service
@Transactional
public class DownIncomeBillServiceImpl extends AbstractServiceImpl<Object, Object, DownIncomeBillVo, DownIncomeBill, Long> implements DownIncomeBillService {
  @Autowired
  private DownIncomeBillRepository downstreamIncomeBillRepositoryImpl;

  @Override
  protected AggregateRepository<DownIncomeBill, Long> getAggregateRepository() {
    return downstreamIncomeBillRepositoryImpl;
  }

  /**
   * 确认生效
   *
   * @param id
   * @return
   */
  @Override
  public Boolean confirmState(Long id) {
    DownIncomeBill downIncomeBill = downstreamIncomeBillRepositoryImpl.getById(id);
    downIncomeBill.confirmState();
    downstreamIncomeBillRepositoryImpl.update(downIncomeBill);

    //在事件里面做了双方确认(意思就是双方确认之后才纳入应收付记录和汇总)
    if (downIncomeBill.getState().equals(DownIncomeBillEnum.CONFIRM.getStatus()) && downIncomeBill.getConfirmState().equals(DownIncomeBillEnum.OTHERPARTY_CONFIRM.getStatus())) {
      Object[] obj = new Object[]{downIncomeBill};
      //发送事件消息
      this.publicEvent(DownIncomeBillEvent.buildDownIncomeBillStateConfirmEvent(obj));
    }
    return Boolean.TRUE;
  }

  /**
   * 取消生效
   *
   * @param id
   * @return
   */
  @Override
  public Boolean cancelConfirm(Long id) {
    DownIncomeBill downIncomeBill = downstreamIncomeBillRepositoryImpl.getById(id);
    downIncomeBill.cancelConfirm();
    downstreamIncomeBillRepositoryImpl.update(downIncomeBill);

    //当服务商已经确认时
    if (downIncomeBill.getState().equals(DownIncomeBillEnum.CONFIRM.getStatus())) {
      Object[] obj = new Object[]{downIncomeBill};
      this.publicEvent(DownIncomeBillEvent.buildDownIncomeBillStateUnConfirmEvent(obj));
    }
    return Boolean.TRUE;
  }

  /**
   * 上传单据图片
   *
   * @param dto
   */
  @Override
  public void upload(FilesDto dto) {
    DownIncomeBill bill = downstreamIncomeBillRepositoryImpl.getById(dto.getId());
    bill.upload(dto);
    downstreamIncomeBillRepositoryImpl.upload(bill);
  }

  /**
   * 消费者：监听对账单（生成对账单状态和对账单号）
   *
   * @param bill
   */
  @DomainEventHandle(DownStatementAccountBillEvent.DOWN_STATEMENT_BILL_ACCOUNT_CREATED)
  protected void handleDownStatementBillAccountCreated(DownStatementAccountBill bill) {
    bill.getDownStatementAccountBillItems().forEach(item -> {
      if (item.getSourceType() == DownStatementAccountBillEnum.SOURCE_INCOME_BILL.getStatus()) {
        DownIncomeBill incomeBill = downstreamIncomeBillRepositoryImpl.getById(item.getSourceId());
        incomeBill.generating(bill.getId());
        downstreamIncomeBillRepositoryImpl.upload(incomeBill);
      }
    });
  }
  /**
   * 消费者：监听对账单（修改对账单状态）
   *
   * @param bill
   */
  @DomainEventHandle(DownStatementAccountBillEvent.DOWN_STATEMENT_BILL_ACCOUNT_UPDATA)
  protected void handleDownStatementBillAccountUpdata(DownStatementAccountBill bill) {
    Wrapper wrapper = Wrapper.build();
    wrapper.append(Restrictions.eq("statementOfAccountId",bill.getId()));
    List<DownIncomeBill> downIncomeBillList = downstreamIncomeBillRepositoryImpl.getList(wrapper);
    downIncomeBillList.forEach(downIncomeBill -> {
      downIncomeBill.cancelGenerating();
      downstreamIncomeBillRepositoryImpl.upload(downIncomeBill);
    });
    bill.getDownStatementAccountBillItems().forEach(item -> {
      if (item.getSourceType() == DownStatementAccountBillEnum.SOURCE_INCOME_BILL.getStatus()) {
        DownIncomeBill incomeBill = downstreamIncomeBillRepositoryImpl.getById(item.getSourceId());
        incomeBill.generating(bill.getId());
        downstreamIncomeBillRepositoryImpl.upload(incomeBill);
      }
    });
  }

  /**
   * 消费者：监听对账单（删除对账单状态和对账单号）
   *
   * @param bill
   */
  @DomainEventHandle(DownStatementAccountBillEvent.DOWN_STATEMENT_BILL_ACCOUNT_DESTORY)
  protected void handleDownStatementBillAccountDestory(DownStatementAccountBill bill) {
    bill.getDownStatementAccountBillItems().forEach(item -> {
      if (item.getSourceType() == DownStatementAccountBillEnum.SOURCE_INCOME_BILL.getStatus()) {
        DownIncomeBill incomeBill = downstreamIncomeBillRepositoryImpl.getById(item.getSourceId());
        incomeBill.cancelGenerating();
        downstreamIncomeBillRepositoryImpl.upload(incomeBill);
      }
    });
  }
}
